// miniprogram/pages/admin/portfolio/newPortfolio/newPortfolio.js
const MAX_IMAGE_SIZE = 1024*1024*1024;
const uploader = require('../../../utils/upload.js');
const util = require('../../../utils/util.js');
const app = getApp();

Page({
  removeImages: [],
  /**
   * 页面的初始数据
   */
  data: {
    portfolio: {},

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
    app.login(user=>{
      if (!user.studioid) {
        wx.navigateBack();
        return;
      }
      if (options._id){
        wx.setNavigationBarTitle({
          title: '作品编辑',
        })
        this.loadItems(options, user)
      }
    });
  },
  isEditing(e) {
    console.log('isEditing',e.detail)
    this.setData({
      isEditing: e.detail.isEditing
    })
  },
  changeCategory: function(e){
    const category = this.data.portfolio.category;
    const that = this;
    wx.navigateTo({
      url: `/pages/admin/category/category?category=${category}`,
      events: {
        'changeCategory': function(res){
          that.setData({['portfolio.category']: res.item});
        }
      }
    })
  },

  loadItems: function(options, user){
    wx.showNavigationBarLoading();
    wx.cloud.callFunction({
      name: 'crud',
      data: {
        op: 'get',
        table: 'portfolio',
        where: {_id: options._id, studioid: user.studioid}
      },
      success: res=>{
        if (res.result.data && res.result.data.length > 0)
        this.setData({portfolio: res.result.data[0]})
        wx.hideNavigationBarLoading();
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  submitData: function(portfolio){
    const that = this;
    wx.showLoading({
      title: '正在保存数据',
    })
    wx.cloud.callFunction({
      name: 'crud',
      data:{
        table: 'portfolio',
        op: 'update',
        data: portfolio
      },
      success: res=>{
   
        console.log(res.result);
        wx.hideLoading();
        let pages = getCurrentPages();
        if (res.result._id || res.result.stats.updated){
          if (pages.length > 1){
            pages[pages.length-2].onLoad();
          }
          wx.navigateBack();
        }
      },
      fail: err=>{
        console.log(err);
        wx.showToast({
          title: err.errMsg,
          icon: 'none'
        })
      }
    })
  },

  apply: function(e){
    let portfolio = this.data.portfolio;

    for(var n in e.detail.value){
      portfolio[n] = e.detail.value[n]
    }
    if (!portfolio._id){
      if (app.globalData.user.studioid){
        portfolio.studioid = app.globalData.user.studioid;
      }else{
        wx.showModal({
          title: '提示',
          content: '您没有对应工作室，请创建或由主账号邀请加入',
          showCancel: false,
          success: r=>{
            if (r.confirm){
              wx.navigateTo({url: '../../studio/studio'})
            }
          }
        })
        return;
      }
      portfolio.visit = 0;
      portfolio.sticky = 0; // TODO 设置为下拉框的值
    }
    // portfolio.category = '儿童'; // TODO 设置为下拉框的值
    portfolio.updatetime = util.formatTime(new Date());
    portfolio.nodes = this.selectComponent('#zEditor').data.nodes;
    portfolio.samples = this.selectComponent('#dragger').data.items;
   
      this.submitData(portfolio);
   
  },

  titleChange: function(e){
    this.setData({['portfolio.title']: e.detail.value});
  },

  chooseImg: function(){
    const that = this;
    wx.navigateTo({
      url: '../../gallary/gallary',
      success: res=>{
        res.eventChannel.on('setImages', items=>{
          if (items.length >= 1)
            that.setData({['portfolio.cover']: items[0]});
        });
        res.eventChannel.emit('setImages', {count: 1});
      }
    })
  },
  // chooseImg: function(){
  //   let that = this;
  //   wx.chooseImage({
  //     sizeType: ['compressed'],
  //     count: 1,
  //     success: res => {
  //       res.tempFiles.map((tempFile, index) => {
  //         if (tempFile.size > MAX_IMAGE_SIZE){
  //           wx.showToast({
  //             title: '图片过大，请重新选择',
  //             icon: 'none'
  //           })
  //           return;
  //         }
  //         // TODO 如果文件较大，自动启用压缩
  //         wx.getImageInfo({
  //           src: tempFile.path,
  //           success: r => {
  //             let cover = {
  //               src: tempFile.path,
  //               size: tempFile.size,
  //               width: r.width / r.height,
  //               uploaded: false
  //             }
  //             if (that.data.portfolio.cover && that.data.portfolio.cover.uploaded){
  //               that.removeImages.push(that.data.portfolio.cover.src);
  //             }
  //             that.setData({['portfolio.cover']: cover});
  //           }
  //         })
  //       });
  //     },
  //   })
  // }
})